package org.geektimes.configuration.microprofile.servlet.listener;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigBuilder;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

/**
 * @Author: jipeng
 * @Description:
 * @Date: Created in 2021/3/27 15:07
 */
public class ConfigServletRequestListener implements ServletRequestListener {

    private static final ThreadLocal<Config> configThreadLoacl = new ThreadLocal<>();

    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
        ServletRequest request = servletRequestEvent.getServletRequest();
        ServletContext servletContext = request.getServletContext();

        System.out.println("Request ServletContext "+servletContext);
        System.out.println("ServletRequestEvent ServletContext "+ servletRequestEvent.getServletContext());

        ClassLoader classLoader = servletContext.getClassLoader();


        ConfigProviderResolver configProviderResolver = ConfigProviderResolver.instance();
        Config config = configProviderResolver.getConfig(classLoader);

        configThreadLoacl.set(config);
    }


    public static Config getConfig(){
        return configThreadLoacl.get();
    }



    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        configThreadLoacl.remove();
    }


}
